//
//  YJMainViewController.swift
//  微博
//
//  Created by YJW on 16/8/4.
//  Copyright © 2016年 yijiang. All rights reserved.
//

import UIKit

//主控制器
class YJMainViewController: UITabBarController {
    
    private lazy var composeBtn:UIButton = UIButton()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setUpChildControllers()
        
        setComposeBtn()
    }
    
    @objc private func composeClick(){
        print("撰写微博")
        
        let vc = UIViewController()
        vc.view.backgroundColor = #colorLiteral(red: 0.4028071761, green: 0.7315050364, blue: 0.2071235478, alpha: 1)
        let nav = UINavigationController(rootViewController: vc)
        present(nav, animated: true, completion: nil)
    }
    
    /*
     portrait：肖像，竖屏
     landscape：风景，横屏
     
     - 使用代码控制设备的方向，好处：可以在需要横屏的时候单独处理！
     - 设置支持的方向之后，当前的控制器及子控制器都会遵守这个方向！
     - 如果播放视频，通常是通过 modal 展现的！(好像是 present 方法)
     */
    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return .portrait
    }
    
}

/*
 extension 类似于 OC 中的分类，在 Swift 中还可以用来切分代码块（可以把相近功能的函数，放在一个 extension 中，便于维护代码）
 注：和 OC 的分类一样，extension 中不能定义属性
 */
//MARK: - 设置界面 
extension YJMainViewController{
    
    //设置撰写按钮
    private func setComposeBtn(){
        composeBtn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: UIControlState(rawValue: 0))
        composeBtn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: UIControlState(rawValue: 0))
        
        let count = CGFloat(childViewControllers.count)
        
        // 将按钮宽度增大一点，盖住容错点
        let w = tabBar.bounds.width / count - 1
        
        composeBtn.frame = tabBar.bounds.insetBy(dx: w * 2, dy: 0)
        
        tabBar.addSubview(composeBtn)
        
        composeBtn.addTarget(self, action: #selector(composeClick), for: .touchUpInside)
    }
    
    //设置所有子控制器
    private func setUpChildControllers(){
        
        //在现在的很多应用程序中，界面的创建都依赖网络的 json
//        let array :[[String:AnyObject]] = [
//            ["clsName":"YJHomeViewController","title":"首页","imageName":"home",
//             "visitorInfo":["imageViewName":"","message":"关注一些人，回这里看看有什么惊喜"]],
//            ["clsName":"YJMessageViewController","title":"消息","imageName":"message",
//             "visitorInfo":["imageViewName":"visitordiscover_image_message","message":"登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]],
//            ["clsName":"UIViewController"],
//            ["clsName":"YJDiscoverViewController","title":"发现","imageName":"discover",
//             "visitorInfo":["imageViewName":"visitordiscover_image_profile","message":"登录后，最新、最热微博尽在掌握，不再会与实时潮流擦肩而过"]],
//            ["clsName":"YJMeViewController","title":"我","imageName":"profile"
//                ,"visitorInfo":["imageViewName":"visitordiscover_image_profile","message":"登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]]
//        ]
//        
//        //测试数据格式是否正确 - 转换成 plist 数据更加直观
//        (array as NSArray).write(toFile: "/Users/macbookpro/Documents/YijiangWang/PrivateWorking/微博/weibo.plist", atomically: true)
//        
//        let data = try! JSONSerialization.data(withJSONObject: array, options: .prettyPrinted)
//        (data as NSData).write(toFile: "/Users/macbookpro/Documents/YijiangWang/PrivateWorking/微博/weibo.json", atomically: true)
        
        
        //优先从沙盒中获取网络数据
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let path1 = (docDir as NSString).appendingPathComponent("weibo.json")
        
        var data = NSData(contentsOfFile: path1)
        
        if data == nil {
            
            //1.获取路径 /2.加载NSData /3.反序列化转换成数组
            let path2 = Bundle.main().pathForResource("weibo.json", ofType: nil)
            data = NSData(contentsOfFile: path2!)
        }
        
        guard let array = try? JSONSerialization.jsonObject(with: (data as? Data)!, options: []) as! [[String:AnyObject]] else{
            
            return
        }
        
        
        
        //遍历数组，循环创建控制器数组
        var arrayM = [UIViewController]()
        
        for diction in array {
            
            arrayM.append(controller(dict: diction))
        }
        
        //设置 tabBar 的子控制器
        viewControllers = arrayM
    }
    
    /**
     使用字典创建一个子控制器
     - parameter dict:信息字典[clsName,title,imageName,visitorInfo]
     - returns:子控制器
     */
    private func controller(dict:[String:AnyObject]) -> UIViewController{
        
        //1.取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"]  as? String,
            let cls = NSClassFromString(Bundle.main().namespace + "." + clsName) as? YJBaseViewController.Type,
        let visitorInfo = dict["visitorInfo"] as? [String:String]
        
            else {
            
                return UIViewController()
        }
        
        //2.创建视图控制器
        let vc = cls.init()
        vc.title = title
        vc.visitorDictionary = visitorInfo
        
        //3.设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_highlighted")?.withRenderingMode(.alwaysOriginal)
        
        //4.通过属性字典更改按钮的颜色和大小
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange()], for: .highlighted)
        //默认大小为 12 号字，修改字体大小，只能设置 normal 的字体大小，设置成高亮的无效
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13)], for: UIControlState(rawValue: 0))
        
        let nav = YJNavigationController(rootViewController: vc)
        
        return nav;
        
    }
    
}



